<route lang="json5">
{
  needLogin: true,
  style: {
    navigationBarTitleText: '我的课程',
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <view>
    <!-- 顶部导航栏 -->
    <wd-navbar
      placeholder
      fixed
      safeAreaInsetTop
      :bordered="false"
      :leftArrow="false"
      title="我的课程"
      custom-class="!bg-white !border-b-none"
    ></wd-navbar>
    <!-- 课程分类标签 -->
    <view class="h-92rpx bg-[#FFFFFF] flex items-center justify-evenly">
      <view
        @click="handleActive(0)"
        class="font-bold relative"
        :class="
          activeTab === 0
            ? 'text-36rpx text-[#333333] lh-49rpx status-info'
            : 'text-30rpx text-[#999999] lh-41rpx'
        "
      >
        全部
      </view>
      <view
        @click="handleActive(1)"
        class="font-bold relative"
        :class="
          activeTab === 1
            ? 'text-36rpx text-[#333333] lh-49rpx status-info'
            : 'text-30rpx text-[#999999] lh-41rpx'
        "
      >
        已发布
      </view>
      <view
        @click="handleActive(2)"
        class="font-bold relative"
        :class="
          activeTab === 2
            ? 'text-36rpx text-[#333333] lh-49rpx status-info'
            : 'text-30rpx text-[#999999] lh-41rpx'
        "
      >
        未发布
      </view>
    </view>

    <!-- 课程列表 -->
    <scroll-view
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="false"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      class="relative overflow-y-auto overflow-scrolling-touch"
    >
      <template v-if="courseList && courseList.length > 0">
        <view v-for="course in courseList" :key="course.id" class="mb-24rpx">
          <wd-swipe-action custom-class="!ml-24rpx !mr-23rpx">
            <view
              @click="handleDetails(course)"
              class="h-321rpx bg-[#FFFFFF] border-rd-[10rpx_10rpx_10rpx_10rpx] mt-91rpx flex relative w-full"
            >
              <view
                class="w-348rpx h-357rpx border-rd-[10rpx_10rpx_10rpx_10rpx] absolute bottom-[30rpx] left-[17rpx]"
              >
                <view
                  class="w-138rpx h-47rpx bg-[rgba(69,138,254,0.3)] border-rd-[0rpx_4rpx_4rpx_0rpx] absolute right-[-138rpx] top-[10rpx] font-bold text-20rpx lh-27rpx flex items-center"
                  :class="
                    course.status == '1'
                      ? 'bg-[rgba(69,138,254,0.3)] text-[#458AFE]'
                      : 'bg-[rgba(254,143,30,0.3)] text-[#FE8F1E]'
                  "
                >
                  <image
                    :src="
                      course.status == '1'
                        ? '/static/images/course/publish-yes.png'
                        : '/static/images/course/publish-no.png'
                    "
                    mode="aspectFill"
                    class="w-32rpx h-32rpx mr-11rpx ml-19rpx"
                  ></image>
                  {{ course.status == '1' ? '已发布' : '未发布' }}
                </view>
                <image :src="course.cover" mode="aspectFill" class="w-full h-full"></image>
              </view>
              <view class="w-[calc(348rpx+17rpx)] shrink-0"></view>
              <view class="ml-22rpx pr-17rpx">
                <view class="font-bold text-34rpx text-[#3D3D3D] lh-47rpx pt-36rpx ellipsis-2">
                  {{ course.name }}
                </view>
                <view class="font-400 text-20rpx text-[#999999] lh-27rpx ellipsis-3 pt-36rpx">
                  {{ course.content }}
                </view>
                <view
                  class="w-198rpx h-54rpx bg-[#F5F5F5] border-rd-[27rpx_27rpx_27rpx_27rpx] flex items-center pl-24rpx mt-36rpx"
                >
                  <image
                    src="/static/images/course/user.png"
                    mode="aspectFill"
                    class="w-26rpx h-26rpx"
                  ></image>
                  <view class="font-bold text-22rpx text-[#B2B5BD] lh-30rpx pl-2rpx">学生：</view>
                  <view class="font-bold text-26rpx text-[#3D3D3D] lh-36rpx pl-22rpx">
                    {{ course.studentCount }}
                  </view>
                </view>
              </view>
            </view>
            <template #right v-if="course.status == '2'">
              <view class="flex h-full text-22rpx font-bold text-[#FFFFFF]">
                <view
                  class="h-full w-160rpx bg-[#00CC7E] border-rd-[0rpx_10rpx_10rpx_0rpx] flex items-center justify-center flex-col"
                  @click="handlePublish(course)"
                >
                  <image
                    class="w-40rpx h-40rpx mb-18rpx"
                    src="/static/images/course/publish.png"
                    mode="scaleToFill"
                  />
                  发布
                </view>
                <view
                  class="h-full w-160rpx bg-[#FF3B30] border-rd-[0rpx_10rpx_10rpx_0rpx] flex items-center justify-center flex-col"
                  @click="handleRemove(course)"
                >
                  <image
                    class="w-40rpx h-40rpx mb-18rpx"
                    src="/static/images/course/remove.png"
                    mode="scaleToFill"
                  />
                  删除
                </view>
              </view>
            </template>
          </wd-swipe-action>
        </view>
      </template>
      <template v-else>
        <wd-status-tip
          custom-class="!mt-250rpx h-480rpx"
          image="/static/images/icons/empty.png"
          tip="暂无数据"
        />
      </template>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { addPublishData, getLessonListApi, removeLessonApi } from '@/service/edu/lesson/lessonMain'
import { useToast, useQueue } from 'wot-design-uni'
import { checkForUpdate } from './upgrade/upgrade'

const { closeOutside } = useQueue()

const activeTab = ref(0)
const offsetTop = ref(0)
const pageNum = ref(1)
const courseStatus = ref('')
const isRefreshing = ref(false)
const hasMore = ref(true)

// 课程列表数据
const courseList = ref<any[]>([])
// 计算sticky的偏移量
onMounted(() => {
  fetchCourseList()
  checkVersion()
})
function handleActive(value) {
  activeTab.value = value
}

// App版本检测
async function checkVersion() {
  const upgrade = await checkForUpdate()
  if (upgrade === true) {
    const platform = uni.getSystemInfoSync().platform // 手机平台
    // 安卓手机弹窗升级
    if (platform === 'android') {
      uni.navigateTo({
        url: './upgrade/upgrade',
      })
    }
    // IOS无法在线升级提示到商店下载
    else {
      uni.showModal({
        title: '发现新版本',
        content: '请到App store进行升级',
        showCancel: false,
      })
    }
  }
}

// 获取课程列表数据
const fetchCourseList = async () => {
  const res: any = await getLessonListApi({
    pageNum: pageNum.value,
    pageSize: 10,
    status: courseStatus.value,
  })
  if (res.code === 200) {
    if (pageNum.value === 1) {
      courseList.value = res.rows
    } else {
      courseList.value.push(...res.rows)
    }
    if (courseList.value.length >= res.total) {
      hasMore.value = false
    }
  }
}

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true
  try {
    pageNum.value = 1
    await fetchCourseList()
  } finally {
    isRefreshing.value = false
  }
}
// 加载更多
const loadMore = async () => {
  if (!hasMore.value) return
  pageNum.value++
  await fetchCourseList()
}
// 监听标签切换
watch(activeTab, (newVal: any) => {
  console.log('newVal======', newVal)
  if (newVal === 0 || newVal === '0') {
    courseStatus.value = ''
  } else if (newVal === 1 || newVal === '1') {
    courseStatus.value = '1'
  } else if (newVal === 2 || newVal === '2') {
    courseStatus.value = '2'
  }
  pageNum.value = 1
  fetchCourseList()
})

const handleDetails = (course: any) => {
  closeOutside()
  uni.navigateTo({
    url: `/pages/course/detail?id=${course.id}`,
  })
}
function handlePublish(course) {
  uni.showModal({
    title: '提示',
    content: '确定发布该课程吗？',
    success: async (res) => {
      try {
        if (res.confirm) {
          const data = await addPublishData({
            id: course.id,
            status: '1',
          })
          if (data.code === 200) {
            uni.showToast({
              title: '发布课程成功',
              icon: 'none',
              duration: 1500,
            })
          } else {
            uni.showToast({
              title: data.msg,
              icon: 'none',
              duration: 1500,
            })
          }
          setTimeout(() => {
            pageNum.value = 1
            fetchCourseList()
          }, 500)

          console.log('data====', data)
        }
      } catch (e) {
        console.error('发布失败', e)
      } finally {
        console.info('发布状态')
      }
    },
  })
}
function handleRemove(course) {
  uni.showModal({
    title: '提示',
    content: '确定删除该课程吗？',
    success: async (res) => {
      try {
        if (res.confirm) {
          const data = await removeLessonApi(course.id)
          if (data.code === 200) {
            uni.showToast({
              title: '删除课程成功',
              icon: 'none',
              duration: 1500,
            })
          } else {
            uni.showToast({
              title: data.msg,
              icon: 'none',
              duration: 1500,
            })
          }
          setTimeout(() => {
            pageNum.value = 1
            fetchCourseList()
          }, 500)
        }
      } catch (e) {
        console.error('删除失败', e)
      } finally {
        console.info('删除状态')
      }
    },
  })
}
</script>

<style lang="scss" scoped>
.status-info::after {
  position: absolute;
  bottom: -24rpx;
  left: 26%;
  width: 44rpx;
  height: 9rpx;
  content: '';
  background-color: #3670f7;
  border-radius: 6rpx 6rpx 6rpx 6rpx;
}
</style>
